import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
import * as cache from "../common/cache";
import pageRoute from "../router/page/index";


// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = Router.prototype.push;
const originalReplace = Router.prototype.replace;

// push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch(err => err);
};

//replace
Router.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalReplace.call(this, location, onResolve, onReject);
    return originalReplace.call(this, location).catch(err => err);
};



// 根据views目录动态生成路由
const viewsRoutes = getRoutesByViews()


const router = new Router({
    // mode: 'history',
    // base: '/dist/',
    scrollBehavior(to, from, savedPositon) {
        // history.pushState(null, null, document.URL)
        return {
            x: 0,
            y: 0
        }
    },

    routes: pageRoute.concat(viewsRoutes)

});


router.beforeEach((to, from, next) => {
    // console.log('router.beforeEach', to, from)
    window.scrollTo(0,0)
    if (to.path === '/') {
        // 是否有用户信息
        if (cache.hasUserInfo) {
            next()
        } else {
            next({
                path: '/login'
            })
        }
    } else {
        // 判断该路由是否需要登录权限
        if (to.matched.some(item => item.meta.requireAuth)) {
            if (cache.hasUserInfo()) {
                next()
            } else {
                next({
                    path: '/login',
                    // 将跳转的路由path作为参数，登录成功后跳转到该路由
                    query: {redirect: to.fullPath}
                })
            }
        } else {
            next()
        }
    }


});


/**
 * 根据views目录动态生成路由
 * 如: views/template目录下有index、cm、detail三个页面，
 * index作为展示页面路由路径为 /template
 * 其他页面则为 /template/cm 和 /template/detail
 */
function getRoutesByViews() {
    const files = require.context('../views', true, /.vue/)
    let pages = {};
    //生成路由规则
    let tempRoutes = [];
    files.keys().forEach(key => {
        pages[key.replace(/(\.\/|\.vue)/g, '')] = files(key).default;
    });
    // console.log('getRoutesByViews page', pages)
    //生成所有路由
    Object.keys(pages).forEach(item => {
        const split = item.split('/')
        // console.log('路由路径', item, split)
        if (item !== 'App' && split.length > 0) {
            let path
            let name
            // 目录下index.vue, 去掉index只取前缀作为路由路径和名称
            if (split[split.length - 1] === 'index') {
                const prefix = split.slice(0, split.length - 1).join('/')
                path = `/${prefix}`
                name = `/${prefix}`
            } else {
                path = `/${item}`
                name = `/${item}`
            }
            tempRoutes.push({
                path: path,
                name: name,
                component: pages[item],
                meta: {
                    requireAuth: true,
                },
            })
        }
    });

    const routes =   {
        path: "/layout",
        name: "/layout",
        component: resolve => require(["../page/layout.vue"], resolve),
        meta: {
            requireAuth: true
        },
        children: tempRoutes
    }

    // console.log('getRoutesByViews', routes)
    return routes
}

export default router
